package com.unitd.filesystem.comm;

import com.unitd.frame.comm.utils.BeanUtils;

import java.io.Serializable;

/**
 * 文件类型信息, 用于定义文件系统支持的上传、下载的文件类型
 *
 * @author Hudan
 * @version 1.0
 * @filename FileType.java
 * @copyright www.unitd.com
 * @date 2017/3/6
 */
public enum FileType implements Serializable {
	/** 允许上传的文件类型 */
	JPG(".jpg", "image/jpeg"),
	GIF(".gif", "image/gif"),
	PNG(".png", "image/png"),
	BMP(".bmp", "image/bmp"),
	TXT(".txt", "text/plain"),
	MP3(".mp3", "audio/mpeg3"),
	AVI(".avi", "video/avi"),
	MP4(".mp4", "audio/mp4"),
	AMR(".amr", "audio/amr"),
	WAV(".wav", "audio/wav"),
	ZIP(".zip", "application/zip"),
	GZIP(".gzip", "application/x-gzip"),
	GZ(".gz", "application/x-gzip"),
	STREAM("", "application/octet-stream"),
	JS(".js", "text/plain"),
	HTML(".html", "text/html"),
	HEX(".hex", "application/octet-stream"),
	LSF(".lsf", "application/octet-stream"),
	SVG(".svg", "application/x-shockwave-flash"),
	PDF(".pdf", "application/pdf"),
	DOC(".doc", "application/msword"),
	DOCX(".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"),
	XLS("application/vnd.ms-excel", ".xls"),
	XLSX(".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"),
	PPT(".ppt", "application/vnd.ms-powerpoint"),
	PPTX(".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation");

	/** 文件名后缀 */
	private final String suffix;
	/** 文件的MIME类型 */
	private final String mimeType;

	FileType(String suffix, String mimeType) {
		this.suffix = suffix;
		this.mimeType = mimeType;
	}

	public String getMimeType() {
		return mimeType;
	}

	public String getSuffix() {
		return suffix;
	}

	/**
	 * @param suffix 不包括.的文件后缀名
	 * @return FileType
	 * @desc 根据文件类型名称(不包括.的文件后缀名)获取对应的文件类型对象
	 */
	public static FileType getFileTypeBySuffix(String suffix) {
		FileType fs = FileType.valueOf(suffix.toUpperCase());

		if (BeanUtils.isNull(fs)) {
			throw new RuntimeException("暂不支持[" + suffix + "]文件类型");
		}
		return fs;
	}

	/**
	 * @param bytes 文件字节流
	 * @return JPG, GIF, PNG or null
	 * @desc 获取文件的真实后缀名。目前只支持JPG, GIF, PNG, BMP四种图片文件。
	 */
	public static FileType getFileSuffix(byte[] bytes) {
		if (bytes == null || bytes.length < 10) {
			return null;
		}

		if (bytes[0] == 'G' && bytes[1] == 'I' && bytes[2] == 'F') {
			return FileType.GIF;
		} else if (bytes[1] == 'P' && bytes[2] == 'N' && bytes[3] == 'G') {
			return FileType.PNG;
		} else if (bytes[6] == 'J' && bytes[7] == 'F' && bytes[8] == 'I' && bytes[9] == 'F') {
			return FileType.JPG;
		} else if (bytes[0] == 'B' && bytes[1] == 'M') {
			return FileType.BMP;
		} else {
			return null;
		}
	}

	public static void main(String[] args) {
		FileType tt = getFileTypeBySuffix(".jpg");
		System.out.println(tt.toString());
	}
}